import paho.mqtt.client as mqtt
import json
import asyncio
from utils.logger import logger
from receiver.topic_dispatcher import TopicDispatcher
from config import Config

MQTT_BASIC_AIRCRAFT_TOPIC = "px4/" + Config.SERIAL_NUMBER + "/service/basicAircraftService"
MQTT_DRONE_CONTROL_TOPIC = "px4/" + Config.SERIAL_NUMBER + "/drc/down"
MQTT_STATUS_TOPIC = "px4/" + Config.SERIAL_NUMBER + "/osd"

topicDispatcher = TopicDispatcher()


class MQTTClient:
    def __init__(self, broker, port, drone_controller, loop):
        self.broker = broker
        self.port = port
        self.drone_controller = drone_controller
        self.loop = loop  # 传递事件循环
        self.client = mqtt.Client()
        self.client.on_connect = self.on_connect
        self.client.on_message = self.on_message

    def on_connect(self, client, userdata, flags, rc):
        logger.info("MQTT 连接成功")
        self.client.subscribe(MQTT_BASIC_AIRCRAFT_TOPIC)
        self.client.subscribe(MQTT_DRONE_CONTROL_TOPIC)

    def on_message(self, client, userdata, msg):
        payload = msg.payload.decode()
        topic = msg.topic
        try:
            message = json.loads(payload)
            # 使用传递的事件循环调度协程
            asyncio.run_coroutine_threadsafe(
                topicDispatcher.handler_message(message, topic),
                self.loop
            )
        except json.JSONDecodeError:
            logger.error("无效的 JSON 格式")

    def connect(self):
        self.client.connect(self.broker, self.port, 60)
        self.client.loop_start()

    def publish_status(self, status):
        self.client.publish(MQTT_STATUS_TOPIC, json.dumps(status))
        logger.debug(f"发布状态: {status}")
